import { Route, Redirect, useLocation } from "react-router-dom"
import { isAuth } from "@/utils/token"

const AuthRoute = ({
  //优化组件封装
  children,
  component: Component,
  ...rest
}) => {
  const location = useLocation()
  // console.log("location", location) 通过useLocation拿到路由对象
  return (
    <Route
      {...rest}
      render={() =>
        //-props 优化
        {
          // console.log("props", props)
          //判断是否登录
          if (!isAuth()) {
            //未登录
            return (
              <Redirect
                // to={"/login"} Redirect组件的to属性川传值，除了传字符串类型还能传对象类型
                to={{
                  pathname: "/login",
                  //通过路由传递额外的参数
                  state: {
                    from: location.pathname,
                  },
                }}
              />
            )
          }
          return children ? (
            children
          ) : (
            <Component
            // -{...props} 优化
            />
          )
        }
      }
    />
  )
}

export { AuthRoute }
